import os, sys
# sys.path.append(os.path.join(os.path.dirname(__file__),'..'))
sys.path.append('./insightface/deploy')
sys.path.append('./insightface/src/common')


from imutils import paths
import face_preprocess
import onnx_if as inf
import cv2
import numpy as np


import argparse
from builtins import range
#from tensorrtserver.api import *
#import tritongrpcclient
import tritonclient.http as httpclient
from tritonclient.utils import InferenceServerException


def cos_sim(feature_1,feature_2):
    return np.dot(feature_1,feature_2)/(np.linalg.norm(feature_1)*np.linalg.norm(feature_2))

def findCosineDistance(vector1, vector2):
    vec1 = vector1.flatten()
    vec2 = vector2.flatten()
    a = abs(np.dot(vec1.T, vec2))
    b = np.dot(vec1.T, vec1)
    c = np.dot(vec2.T, vec2)
    return 1 - (a/(np.sqrt(b)*np.sqrt(c)))

vis_thres=0.6
def get_feature(triton_client,image_url):
    model_name = "arcface-100"
    model_version = 1
    batch_size = 1
    #infer_ctx = InferContext('localhost:28001', protocol, model_name, model_version,http_headers=None, verbose=False)
    img_raw = cv2.imread(image_url+'.jpg')
    bboxes = inf.onnx_inference(img_raw)
    if len(bboxes) != 0:
        for bboxe in bboxes:
            if bboxe[4] < vis_thres:
                continue
            print(len(bboxe))
            bbox = np.array([bboxe[0], bboxe[1], bboxe[2], bboxe[3]])
            landmarks = np.array([bboxe[5], bboxe[7], bboxe[9], bboxe[11], bboxe[13],bboxe[6], bboxe[8], bboxe[10], bboxe[12], bboxe[14]])
            landmarks = landmarks.reshape((2,5)).T
            nimg = face_preprocess.preprocess(img_raw, bbox, landmarks, image_size='112,112')
            cv2.imwrite(image_url+'_imwrite.jpg', nimg)
            nimg = cv2.cvtColor(nimg, cv2.COLOR_BGR2RGB)
            img_data = np.array(nimg)
            img_data = np.subtract(img_data,127.5)
            img_data = np.true_divide(img_data,128)
            img_data = np.transpose(img_data, (2, 0, 1))
            img_data = np.expand_dims(img_data, 0).astype('float32')
            inputs =[]
            inputs.append(httpclient.InferInput('data', [1, 3, 112, 112], "FP32"))

            outputs = []
            inputs[0].set_data_from_numpy(img_data)

            outputs.append(httpclient.InferRequestedOutput('prob'))
            results = triton_client.infer(
                model_name=model_name, inputs=inputs,  outputs=outputs, headers={"test": "1"}
            )
            feature = np.frombuffer(results.as_numpy("prob"), dtype=np.float32)
            return feature


if __name__ == '__main__':
    try:
        triton_client = triton_client = httpclient.InferenceServerClient(
                url="192.168.0.147:18000", verbose=False
        )
    except Exception as e:
        print("channel creation failed: " + str(e))
        sys.exit()
    feature_1 = get_feature(triton_client,"./img/wy")
    feature_2 = get_feature(triton_client,"./img/lxm2")

    print(cos_sim(feature_1,feature_2))




